package com.jian;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author Jiange
 * @create 2021-09-13-17:46
 */
public class FileLockDemo {
    public static void main(String[] args) throws IOException {
        //是进程级别的  共享锁和排他锁  共：其他的进程可以读  排只有自己读写
//        RandomAccessFile accessFile = new RandomAccessFile("D:\\WEB\\NIO\\NIO.iml", "rw");
//        FileChannel channel = accessFile.getChannel();
        Path path = Paths.get("D:\\WEB\\NIO\\NIO.iml");
        FileChannel channel = FileChannel.open(path,
                StandardOpenOption.WRITE,
                StandardOpenOption.APPEND
                );
        channel.position(channel.size()-1);
        FileLock lock = channel.lock();//默认是排他锁  trylock默认也是排他 是非阻塞的  获取不到就返回null
        boolean shared = lock.isShared();
        boolean valid = lock.isValid();//判断是否还有效
    }
}
